package org.ladybug.service.auth;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.ladybug.dao.persistence.Utente;
import org.skins.io.HexReader;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UsernameNotFoundException;

public class HibernateAuthenticationService implements AuthenticationService {

	private HibernateTemplate hibernateTemplate;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		System.out.println("-------------------------------------------------");
		Utente utente = new Utente();
		utente.setNickname(username);
		utente = getUtenteByCredential(utente);
		System.out.println(utente);
		LadyBugUserDetails userDetails = new LadyBugUserDetails(utente);

		return userDetails;
	}

	private Utente getUtenteByCredential(Utente utente) {
		HibernateTemplate hibernateTemplate = getHibernateTemplate();
		// byte[] keyPassword = new
		// StringBuffer(utente.getNickname()).append(utente.getPassword()).toString().getBytes();
		// keyPassword = MessageDigest.getInstance("SHA").digest(keyPassword);
		// utente.setPassword(HexReader.bytesToHex(keyPassword));
		DetachedCriteria criteria = DetachedCriteria.forClass(Utente.class);
		Criterion crUser = Expression.eq("nickname", utente.getNickname());
		// Criterion crPwd = Expression.eq("password", utente.getPassword());
		// Criterion and = Expression.and(crUser, crPwd);
		// criteria.add(and);
		List result = hibernateTemplate.findByCriteria(criteria);
		if (result.size() == 0) {
			return null;
		}
		utente = (Utente) result.get(0);

		return utente;

	}

	// --------------------------- set e get

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

}
